<?php
class RequestManager extends Module{
	public $request = null;
	public $segments = null;
	public $routes = null;
	public $mapping = null;
	
	public function RequestManager(&$application){
		$this->Module($application);
		
		$request = $_GET['REQUEST'];
		unset($_GET['REQUEST']);
		
		require_once(INC_PATH.'routes.php');
		$this->routes = $routes;
		
		if($request){
			$request = $this->clean_request($request);
		}else{//load home route
			$request = 'home';
		}
		$this->request = $request;
		
		$this->process_segments();
		if(!$mapping = $this->process_route()){// try classic load controller/method if mo route defined
			$mapping = array('controller'=>$this->segments[0],'method'=>($this->segments[1] ? $this->segments[1] : 'home'), 'method_params'=>array());
			if(count($this->segments) > 2){
				foreach(array_slice($this->segments, 2) as $param){
					$mapping['method_params'][] = $param;
				}
			}
		}
		$this->mapping = $mapping;
	}
	
	public function get_mapping(){
		return $this->mapping;
	}
	
	private function process_segments(){
		$this->segments = explode('/', $this->request);
	}
	
	private function process_route(){
		if($this->routes){
			foreach($this->routes as $pattern => $route){
				if(preg_match('`'.$pattern.'`', $this->request, $matches)){
					if($route['params'] && is_array($route['params'])){
						$new_params = array();
						$method_params = array();
						foreach($route['params'] as $key => $val){
							for($i=0;$i<count($matches);$i++){
								$val = str_replace('$'.$i, $matches[$i], $val);
							}
							if(is_numeric($key)){
								$method_params[] = $val;
							}else{
								$new_params[$key] = $val;
							}
						}
						$route['params'] = $new_params;
						if($method_params){
							$route['method_params'] = $method_params;
						}
					}
					return $route;
				}
			}
		}
		return false;
	}
	
	private function clean_request($request){
		$request = substr($request, 1);
		if(APP_URL_SUFIX){
			if(substr($request, strlen($request)-strlen(APP_URL_SUFIX))==APP_URL_SUFIX){
				$request = substr($request, 0, strlen($request)-strlen(APP_URL_SUFIX));
			}
		}
		if($request[strlen($request)-1]=='/'){
			$request = substr($request, 0, strlen($request)-1);
		}
		return $request;
	}
}
?>